﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using Hangjing.Model;
using Hangjing.SQLServerDAL;
using System.Web;
using Hangjing.Common;

namespace Hangjing.Weixin
{
    /// <summary>
    /// 微信打钱，或者发红包给用户
    /// </summary>
    public class WechatPay2User
    {
        protected HttpContext context;
        public RequestHandler rh = null;
        public WechatPay2User(HttpContext context)
        {
            this.context = context;
            new TenpayUtil();

            rh = new RequestHandler(context);
            rh.init();

        }

        /// <summary>
        /// 根据openid，订单号，给用户发企业零钱
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="requestid"></param>
        /// <param name="mondey"></param>
        /// <param name="partner_trade_no"></param>
        /// <returns></returns>
        public apiResultInfo Pay(string openid, decimal mondey, string partner_trade_no)
        {
            rh.setParameter("mch_appid", Constant.MINI_APPID);
            rh.setParameter("mchid", TenpayUtil.partner);
            rh.setParameter("nonce_str", TenpayUtil.getNoncestr());
            rh.setParameter("partner_trade_no", partner_trade_no);
            rh.setParameter("check_name", "NO_CHECK");
            rh.setParameter("openid", openid);
            rh.setParameter("spbill_create_ip", TenpayUtil.GetIP());
            rh.setParameter("amount", (mondey * 100).ToString("#0"));
            rh.setParameter("desc", "你推荐的好友完成订单");
            rh.setKey(TenpayUtil.key);
            return transfers();
        }

        /// <summary>
        /// 发红包
        /// </summary>
        /// <returns></returns>
        public bool query()
        {
            try
            {

                rh.getRequestURL();
                string Postdata = rh.parseXML();
                string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
                HttpHelper objhttp = new HttpHelper();
                objhttp.isToLower = false;
                HttpItem objHttpItem = new HttpItem()
                {
                    URL = url,
                    Encoding = "utf-8",
                    Method = "post",
                    CerPath = @"D:\wwwroot\cert\apiclient_cert.p12",
                    Cer_PWD = TenpayUtil.partner,
                    Postdata = Postdata
                };

                string returnmsg = objhttp.GetHtml(objHttpItem);

                Hangjing.AppLog.AppLog.Info("Postdata=" + Postdata + "\r\nreturnmsg=" + returnmsg);

                System.Xml.XmlDocument d = new System.Xml.XmlDocument();
                d.LoadXml(returnmsg);
                System.Xml.XmlCDataSection n = d.SelectSingleNode("/xml/return_code").FirstChild as System.Xml.XmlCDataSection;
                System.Xml.XmlCDataSection result_code = d.SelectSingleNode("/xml/result_code").FirstChild as System.Xml.XmlCDataSection;


                if (n != null && n.Value == "SUCCESS" && result_code != null && result_code.Value == "SUCCESS")
                {
                    return true;

                }

            }
            catch (Exception ex)
            {
                Hangjing.Common.HJlog.toLog("发红包出错：" + ex);
            }

            return false;

        }

        /// <summary>
        /// 企业付款
        /// </summary>
        /// <returns></returns>
        private apiResultInfo transfers()
        {
            apiResultInfo rs = new apiResultInfo();
            try
            {
                rh.getRequestURL();
                string Postdata = rh.parseXML();
                string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
                HttpHelper objhttp = new HttpHelper();
                objhttp.isToLower = false;
                HttpItem objHttpItem = new HttpItem()
                {
                    URL = url,
                    Encoding = "utf-8",
                    Method = "post",
                    CerPath = @"C:\www\cert\apiclient_cert.p12",
                    Cer_PWD = TenpayUtil.partner,
                    Postdata = Postdata
                };

                string returnmsg = objhttp.GetHtml(objHttpItem);

                Hangjing.AppLog.AppLog.Info("Postdata=" + Postdata + "\r\nreturnmsg=" + returnmsg);

                System.Xml.XmlDocument d = new System.Xml.XmlDocument();
                d.LoadXml(returnmsg);


                System.Xml.XmlCDataSection return_code = d.SelectSingleNode("/xml/return_code").FirstChild as System.Xml.XmlCDataSection;
                System.Xml.XmlCDataSection return_msg = d.SelectSingleNode("/xml/return_msg").FirstChild as System.Xml.XmlCDataSection;
                if (return_code != null && return_code.Value == "SUCCESS")
                {
                    System.Xml.XmlCDataSection result_code = d.SelectSingleNode("/xml/result_code").FirstChild as System.Xml.XmlCDataSection;
                    if (result_code != null && result_code.Value == "SUCCESS")
                    {
                        rs.state = 1;
                    }
                    else
                    {
                        rs.msg = return_msg.Value;
                    }
                }
                else
                {
                    rs.msg = return_msg.Value;
                }

            }
            catch (Exception ex)
            {
                rs.msg = ex.Message;
            }

            return rs;

        }

    }
}
